package com.example.a28693.duanshipin;

import android.media.Image;
import android.os.Bundle;
import android.os.Trace;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.a28693.duanshipin.adapters.PlayerTrackPagerAdapter;
import com.example.a28693.duanshipin.base.BaseActivity;
import com.example.a28693.duanshipin.interfaces.IPlayerCallBack;
import com.example.a28693.duanshipin.presenters.PlayerPresenter;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.List;

public class PlayerActivity extends BaseActivity implements IPlayerCallBack, ViewPager.OnPageChangeListener {

    private ImageView               mControlBtn;
    private PlayerPresenter         mPlayerPresenter;
    private SimpleDateFormat        mMinFormat              = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat        mHourFormat             = new SimpleDateFormat("hh:mm:ss");
    private TextView                mTotalDuration;
    private TextView                mCurrentPosition;
    private SeekBar                 mProgressBar;
    private int                     mCurrentProgress        = 0;
    private boolean                 mIsUserTouchProgressBar = false;
    private ImageView               mPlayNextBtn;
    private ImageView               mPlayPreBtn;
    private TextView                mTrackTitleTv;
    private String                  mTrackTitleText;
    private ViewPager               mTrackPageView;
    private PlayerTrackPagerAdapter mTrackPagerAdapter;
    private boolean                 mIsUserSlidePager       = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        mPlayerPresenter = PlayerPresenter.getmPlayerPresenter();
        mPlayerPresenter.registerViewCallBack(this);
        //playerPresenter.play();
        initView();//初始化控件
        mPlayerPresenter.getPlayList();//在界面初始化以后才去获取数据
        initEvent();//设置监听方法

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }


    /**
     * 给控件设置相关事件
     */
    private void initEvent() {
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO：播放和暂停相互转换
                if (mPlayerPresenter.isPlay()) {
                    mPlayerPresenter.pause();
                } else {
                    mPlayerPresenter.play();
                }
            }
        });

        mProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //触摸时:停止自动更新
                mIsUserTouchProgressBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //离开时：更新进度
                mIsUserTouchProgressBar = false;
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });

        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放上一首
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }
            }
        });

        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放下一首
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }
            }
        });

        mTrackPageView.addOnPageChangeListener(this);
        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePager = true;
                        break;
                }
                return false;
            }
        });

    }

    /**
     * 找到各个控件
     */
    private void initView() {
        mControlBtn = this.findViewById(R.id.play_or_pause_btn);
        mTotalDuration = this.findViewById(R.id.track_duration);
        mCurrentPosition = this.findViewById(R.id.current_position);
        mProgressBar = this.findViewById(R.id.track_seek_bar);
        mPlayNextBtn = this.findViewById(R.id.play_next);
        mPlayPreBtn = this.findViewById(R.id.play_pre);
        mTrackTitleTv = this.findViewById(R.id.track_title);
        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitleTv.setText(mTrackTitleText);
        }
        mTrackPageView = this.findViewById(R.id.track_pager_view);
        //创建适配器,并设置
        mTrackPagerAdapter = new PlayerTrackPagerAdapter();
        mTrackPageView.setAdapter(mTrackPagerAdapter);
    }

    @Override
    public void onPlayStart() {
        //开始播放，开始变暂停
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.pause);
        }
    }

    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.music_play_button);
        }
    }

    @Override
    public void onPlayStop() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.music_play_button);
        }

    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay() {

    }

    @Override
    public void onPrePlay() {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        if (mTrackPagerAdapter != null) {
            mTrackPagerAdapter.setData(list);
        }
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int total) {
        mProgressBar.setMax(total);
        //更新进度条
        String totalDuration;
        String currentPosition;
        if (total > 1000 * 60 * 60) {
            totalDuration = mHourFormat.format(total);
            currentPosition = mHourFormat.format(currentProgress);
        } else {
            totalDuration = mMinFormat.format(total);
            currentPosition = mMinFormat.format(currentProgress);
        }
        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration);
        }
        //更新当前时间
        if (mCurrentPosition != null) {
            mCurrentPosition.setText(currentPosition);
        }
        //更新进度:手动/自动
        //计算当前进度
        if (!mIsUserTouchProgressBar) {
            mProgressBar.setProgress(currentProgress);
        }
    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        //设置当前节目标题
        this.mTrackTitleText = track.getTrackTitle();
        if (mTrackTitleTv != null) {
            mTrackTitleTv.setText(mTrackTitleText);
        }
        //当节目改变时，获取当前播放位置
        //节目变化时图片跟着变化
        if (mTrackPageView != null) {
            mTrackPageView.setCurrentItem(playIndex, true);
        }
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int position) {
        //页面选中时切换播放内容
        if (mIsUserSlidePager&&mPlayerPresenter != null) {
            mPlayerPresenter.playByIndex(position);
        }
        mIsUserSlidePager = false;

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }
}
